package com.forlove.app.common.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.forlove.app.ForloveApplication;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 检查权限的工具类
 */
public class PermissionsChecker {
    private static final String TAG = "PermissionsChecker";
    // private static final String TAG = "yjl";
    private static PermissionsChecker instance = null;
    private static String IMEI = "00000000";
    private String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.INTERNET,
            Manifest.permission.SYSTEM_ALERT_WINDOW
//            Manifest.permission.ACCESS_COARSE_LOCATION,
//            Manifest.permission.ACCESS_FINE_LOCATION,
//            Manifest.permission.READ_CONTACTS
    };
    private ArrayList<String> lackPermission;

    public static PermissionsChecker getInstance() {

        if (instance == null) {
            instance = new PermissionsChecker();
        }
        return instance;
    }

    public String getDeviceIMEI(Activity mActivity) {
        boolean hasPermission =
                PermissionsChecker.getInstance().lacksPermission(mActivity,
                        Manifest.permission.READ_PHONE_STATE);
        if (!hasPermission) {
            try {
                LogUtil.d(TAG, "已经获得权限:" + Manifest.permission.READ_PHONE_STATE);
                TelephonyManager TelephonyMgr =
                        (TelephonyManager) ForloveApplication.getInstance().getSystemService(
                                Context.TELEPHONY_SERVICE);
                IMEI = TelephonyMgr.getDeviceId();
            } catch (Exception e) {
                LogUtil.e(TAG, e.getMessage());
            }
        }
        return IMEI;
    }

    /**
     * 判断权限集合
     *
     * @param permissions
     * @return {@true} 已经授权 {@false}未授权
     */
    public boolean lacksPermissions(Activity mActivity, String... permissions) {
        for (String permission : permissions) {
            if (lacksPermission(mActivity, permission)) {
                if (lackPermission == null) {
                    lackPermission = new ArrayList<String>();
                }
                lackPermission.add(permission);
            }
        }
        if (lackPermission != null && lackPermission.size() > 0) {
            return false;
        }
        return true;
    }

    // 判断是否缺少权限
    public boolean lacksPermission(Activity mActivity, String permission) {
        return ContextCompat.checkSelfPermission(mActivity, permission) == PackageManager.PERMISSION_DENIED;
    }

    public void requestReadStatePermission(Activity mActivity) {
        // 单独获取
        // 23版本上检查READ_PHONE_STATE权限，涉及到设备号需要单独获取
        boolean hasPermission =
                PermissionsChecker.getInstance().lacksPermission(mActivity,
                        Manifest.permission.READ_PHONE_STATE);
        if (hasPermission) {
            LogUtil.e(TAG, "请求权限:" + Manifest.permission.READ_PHONE_STATE);
            if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity,
                    Manifest.permission.READ_PHONE_STATE)) {
                // 用户拒绝授权
                LogUtil.e(TAG, "用户拒绝授权");
                return;
            }
            ActivityCompat.requestPermissions(mActivity,
                    new String[]{Manifest.permission.READ_PHONE_STATE}, 0);

        } else {
            try {
                LogUtil.d(TAG, "已经获得权限:" + Manifest.permission.READ_PHONE_STATE);
                TelephonyManager TelephonyMgr =
                        (TelephonyManager) ForloveApplication.getInstance().getSystemService(
                                Context.TELEPHONY_SERVICE);
                IMEI = TelephonyMgr.getDeviceId();
            } catch (Exception e) {
                LogUtil.e(TAG, e.getMessage());
            }
        }
    }

    public void RequesetPermission(Activity mActivity) {
        // requestReadStatePermission();
        PermissionsChecker.getInstance().lacksPermissions(mActivity, permissions);
        if (lackPermission != null && !lackPermission.isEmpty()) {
            String[] lacks = new String[lackPermission.size()];
            for (int i = 0; i < lackPermission.size(); i++) {
                lacks[i] = lackPermission.get(i);
            }
            lackPermission.clear();
            ActivityCompat.requestPermissions(mActivity, lacks, 0);
        }
    }

//    public void showRequestDialog(final Activity mActivity) {
//        if (mActivity == null) {
//            return;
//        }
//        final YJDRegisterInfoDialog dialog = new YJDRegisterInfoDialog(mActivity);
//        dialog.setMesseage1Text("为了我们的功能完整使用，请您设置“本地文件存储”权限", null);
//        dialog.setMesseage2Text("请前往“设置->应用管理->医界贷->权限->存储”进行设置", null);
//        dialog.setRightButtonAvaliable(true);
//        dialog.setRightButtonOnClick(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                if (dialog.isShowing()) {
//                    dialog.dismiss();
//                }
//                getAppDetailSettingIntent(mActivity);
//            }
//        }, "前往设置");
//        dialog.setLeftButtonOnClick(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                dialog.dismiss();
//            }
//        });
//        dialog.show(false);
//    }

    public static void getAppDetailSettingIntent(Context mActivity) {
        try {
            if (mActivity == null) {
                return;
            }
            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", mActivity.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                localIntent.setAction(Intent.ACTION_VIEW);
                localIntent.setClassName("com.android.settings",
                        "com.android.settings.InstalledAppDetails");
                localIntent.putExtra("com.android.settings.ApplicationPkgName",
                        mActivity.getPackageName());
            }
            mActivity.startActivity(localIntent);
        } catch (Exception e) {
            LogUtil.e(e.getMessage());
        }
    }

    public static void getAppDetailSettingIntent(Activity mActivity, Intent localIntent, int requestCode) {
        try {
            if (mActivity == null) {
                return;
            }
            if (localIntent == null) {
                localIntent = new Intent();
            }
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", mActivity.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                localIntent.setAction(Intent.ACTION_VIEW);
                localIntent.setClassName("com.android.settings",
                        "com.android.settings.InstalledAppDetails");
                localIntent.putExtra("com.android.settings.ApplicationPkgName",
                        mActivity.getPackageName());
            }
            mActivity.startActivityForResult(localIntent, requestCode);
        } catch (Exception e) {
            LogUtil.e(e.getMessage());
        }
    }


//    public void showRequestFloatViewDialog(final Activity mActivity) {
//        if (mActivity == null) {
//            return;
//        }
//        final YJDRegisterInfoDialog dialog = new YJDRegisterInfoDialog(mActivity);
//        dialog.setMesseage1Text("为了我们的功能完整使用，请您设置“显示悬浮窗”权限", null);
//        dialog.setMesseage2Text("请前往“设置->应用管理->医界贷->权限管理->显示悬浮窗”\n进行设置", null);
//        dialog.setRightButtonAvaliable(true);
//        dialog.setRightButtonOnClick(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                if (dialog.isShowing()) {
//                    dialog.dismiss();
//                }
//                // getAppDetailSettingIntent(mActivity);
//                PermissionsChecker.gotoPermissionSettings(mActivity);
//            }
//        }, "前往设置");
//        dialog.setLeftButtonOnClick(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                dialog.dismiss();
//            }
//        });
//        dialog.show(false);
//        int num = readFloatSetting(mActivity);
//        if (num < 3) {
//            saveFlaotSetting(mActivity, num + 1);
//        }
//    }

    /**
     * 跳转到小米手机浮窗应用权限设置页面
     *
     * @param context 传入app 或者 activity context，通过context获取应用packegename，之后通过packegename跳转制定应用
     * @return 是否是miui
     */
    public static boolean gotoPermissionSettings(Context context) {
        boolean mark = isMIUI();
        if (mark) {
            // 兼容miui v5/v6 的应用权限设置页面，否则的话跳转应用设置页面（权限设置上一级页面）
            try {
                Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                localIntent.setClassName("com.miui.securitycenter",
                        "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
                localIntent.putExtra("extra_pkgname", context.getPackageName());
                context.startActivity(localIntent);
            } catch (ActivityNotFoundException e) {
                // ACTION_DISPLAY_SETTINGS
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                intent.setData(uri);
                context.startActivity(intent);
            }
        } else {
            getAppDetailSettingIntent(context);
        }
        return mark;
    }


    /**
     * 判断MIUI的悬浮窗权限
     *
     * @param context
     * @return
     */
    public static boolean isMiuiFloatWindowOpAllowed(Context context) {
        final int version = Build.VERSION.SDK_INT;

        if (version >= 19) {
            return checkOp(context, 24); // 自己写就是24 为什么是24?看AppOpsManager
            // 即AppOpsManager.OP_SYSTEM_ALERT_WINDOW
        } else {
            if ((context.getApplicationInfo().flags & 1 << 27) == 1) {
                return true;
            } else {
                return false;
            }
        }
    }

    public static boolean checkOp(Context context, int op) {
        final int version = Build.VERSION.SDK_INT;

        if (version >= 19) {
            AppOpsManager manager =
                    (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            try {
                if (AppOpsManager.MODE_ALLOWED == (Integer) invokeMethod(manager, "checkOp", op,
                        Binder.getCallingUid(), context.getPackageName())) { // 这儿反射就自己写吧
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        } else {
            Log.e(TAG, "Below API 19 cannot invoke!");
        }
        return false;
    }

    /**
     * 检查手机是否是miui
     *
     * @return
     * @ref http://dev.xiaomi.com/doc/p=254/index.html
     */
    public static boolean isMIUI() {
        String device = Build.MANUFACTURER;
        System.out.println("Build.MANUFACTURER = " + device);
        if (device.equals("Xiaomi")) {
            System.out.println("this is a xiaomi device");
            return true;
        } else {
            return false;
        }
    }


    /**
     * 判断是否是miui V5/V6，老的miui无法兼容
     *
     * @param context
     * @return
     */
    public static boolean isMIUIV5V6(Context context) {
        boolean result = false;
        Intent i = new Intent("miui.intent.action.APP_PERM_EDITOR");
        i.setClassName("com.android.settings",
                "com.miui.securitycenter.permission.AppPermissionsEditor");
        if (isIntentAvailable(context, i)) {
            result = true;
        }
        return result;
    }

    /**
     * 判断是否有可以接受的Activity
     *
     * @param context
     * @param intent
     * @return
     */
    public static boolean isIntentAvailable(Context context, Intent intent) {
        PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> list =
                packageManager.queryIntentActivities(intent, PackageManager.GET_ACTIVITIES);
        return list.size() > 0;
    }

    @SuppressLint("NewApi")
    public static int invokeMethod(AppOpsManager manager, String method, int op, int callingUid,
                                   String packageName) throws Exception {
        Class<AppOpsManager> clazz = AppOpsManager.class;
        Method dispatchMethod =
                clazz.getMethod(method, new Class[]{int.class, int.class, String.class});
        int mode =
                (Integer) dispatchMethod
                        .invoke(manager, new Object[]{op, callingUid, packageName});
        return mode;
    }

    public static boolean getLocationPermission(Context context) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            return false;
        } else {
            return true;
        }
    }

    public static boolean getContactsPermission(Context context) {
        return ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
                == PackageManager.PERMISSION_GRANTED ? true : false;
    }


}
